
if(POLICY CMP0012)
  cmake_policy(SET CMP0012 NEW)
endif()

execute_process(
  COMMAND "@PYTHON_EXECUTABLE@"
    "@SimpleITK_SOURCE_DIR@/Utilities/virtualenv/virtualenv.py"
    "--python=@PYTHON_EXECUTABLE@"
    --no-pip
    --no-setuptools
    --clear
    "@PythonVirtualenvHome@"
  RESULT_VARIABLE failed
  ERROR_VARIABLE error
  )

if ( failed )
  message( FATAL_ERROR "Creation of Python virtual enviroment failed.\n${error}" )
endif()

message(STATUS "Installing Python Package: SimpleITK")
execute_process(
  COMMAND "@VIRTUAL_PYTHON_EXECUTABLE@" "@CMAKE_CURRENT_BINARY_DIR@/PythonPackage/setup.py" install
  RESULT_VARIABLE failed
  ERROR_VARIABLE error
  )
if ( failed )
  message( FATAL_ERROR "Installation of SimpleITK into Python virutal enviroment failed.\n${error}" )
endif()


if ( "@SimpleITK_PYTHON_WHEEL@" )
  message(STATUS "Installing Python Package: wheel")
  set(install_wheel_script "
import sys
from ez_setup import use_setuptools
use_setuptools()
if not(sys.modules.get(\"wheel\")):
    from setuptools.command import easy_install
    easy_install.main([\"wheel\"])
")

  execute_process(
    COMMAND @VIRTUAL_PYTHON_EXECUTABLE@ -c "${install_wheel_script}"
    WORKING_DIRECTORY "PythonPackage"
    ERROR_VARIABLE error
    RESULT_VARIABLE failed
    )

  if ( failed )
    message( WARNING ${error} )
  endif()
endif()


execute_process(
  COMMAND "@VIRTUAL_PYTHON_EXECUTABLE@" -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
  OUTPUT_VARIABLE PythonVirtualenvLib
  ERROR_VARIABLE error
  RESULT_VARIABLE failed
  OUTPUT_STRIP_TRAILING_WHITESPACE
  )

if ( failed )
  message( SEND_ERROR "Determining python library patch failed.\n${error}" )
endif()


# Manual numpy installation
execute_process(
  COMMAND "@PYTHON_EXECUTABLE@" -c "import numpy; import os; print(os.path.dirname(numpy.__file__))"
  OUTPUT_VARIABLE numpy_dir
  ERROR_VARIABLE error
  RESULT_VARIABLE failed
  OUTPUT_STRIP_TRAILING_WHITESPACE
  )

if( failed )
  message( WARNING "Failed to determine numpy.__file__ path: \"${error}\"" )
else()

  message( STATUS "Installing numpy from ${numpy_dir} to ${PythonVirtualenvLib}/numpy")

  if ( UNIX )
    execute_process( COMMAND ${CMAKE_COMMAND} -E create_symlink "${numpy_dir}" "${PythonVirtualenvLib}/numpy"
      RESULT_VARIABLE failed
      ERROR_VARIABLE error )
    if ( failed )
      message( SEND_ERROR ${error} )
    endif()
  else ()
    execute_process( COMMAND ${CMAKE_COMMAND} -E copy_directory "${numpy_dir}" "${PythonVirtualenvLib}/numpy"
      RESULT_VARIABLE failed
      ERROR_VARIABLE error )
    if ( failed )
      message( SEND_ERROR ${error} )
    endif()
  endif ()
endif()
